//middleware.go 返回 token 错误401后，怎么处理（重新登录）
function token_err(res){
    if (res.data.code==401) {
        window.location.href = "../login/index.html"
    }
}
let first
//https://juejin.cn/post/7067801027549855757
// axios.defaults.headers.common['Authorization'] = "Bearer "+sessionStorage.getItem('token');
// 允许跨域
axios.defaults.withCredentials = true;
axios.interceptors.request.use(
    config => {
        const token ='Bearer ' + sessionStorage.getItem("token");
       // console.log("===>comm.js token:",token)
        token && (config.headers.Authorization = token);
        return config;
    },
    error => {
        return Promise.error(error);
    }
);
axios.interceptors.response.use(
    response=>{
// 统一定义状态码为200时，表示请求成功，其他请求失败
    console.log("<====comm.js response:",response)
    if (response.status == 200) {

		//--CreateToken
        //token=response.config.headers.Authorization.replace("Bearer ", "")
        //sj=token.split(".")[2]
        //cursj=Date.parse(new Date())/1000
        //if(cursj>sj)
        //    window.location.href = "login.html"
        
		//console.log	("---token--",token)
        if(0){      //  first-----------【后端验证】
            axios.post('controller/user.php?lx=verify', {
                order:this.order,
            }).then((res) => {
                console.log("---res",res)
                first=false  
            }); 
            
        }
        
		//除了 login.html 都要验证(-----【前端验证】)
		if(!window.location.pathname.includes("login.html")){  
			// 解析[conn.php -->getToken()]  本来应该在 php 后台解析token 并验证 userid是否存在
			//https://juejin.cn/post/7036259527729086494
			token=response.config.headers.Authorization.replace("Bearer ", "")
			let strings = token.split("."); //截取token，获取载体
			var userinfo = JSON.parse(decodeURIComponent(escape(window.atob(strings[1].replace(/-/g, "+").replace(/_/g, "/"))))); 
			console.log	("---userinfo--",userinfo)
			sj=userinfo.exp
			cursj=Date.parse(new Date())/1000
			
			//console.log	(sj,cursj)			
			if(cursj>sj)
				window.location.href = "login.html"

            first=true    
		}
	
	//-----???
        //if(response.data.code==401)
        //    window.location.href = "login.html"

        return Promise.resolve(response);
    } else {
        return Promise.reject(response);
    }
},
error=>{
    console.log("error:",error)
    if (error.response.data.code) {
        switch (error.response.data.code) {
            case 401:
                console.log("401");
                //setTimeout(() => {
                window.location.href = "login.html"
                // }, 1000);
                break;
            case 404:
                window.location.href = "../page/404.html"
                break;
        }
    }
    return Promise.reject(error.response);
})